
ctrl={
    url:{
        getGoodsNumber:"",
        imageUpload:"http://www.caizhanzhushou.com/index.php?g=Wechat&m=zhuan&a=xin",
        videoUpload:""
    },
    request:{
      ajax:function(url,param,success,complete){
          $.ajax({
              type:"post",
              url:url,
              data:param,
              dataType:"json",
              timeout:20000,
              success:success,
              error:function(){
                  alert("服务器异常！");
              },
              complete:function(xhr,status){
                  if(status=="timeout"){
                      alert("请求超时！");
                  }
                  complete && complete();
              }

          });
      },
      getGoodsNumber:function(param,success,complete){
          ctrl.request.ajax(ctrl.url.getGoodsNumber,param,success,complete);
      }
    },
    event:{
        delRow:function(ele){
            var self=$(ele);
            var row=self.closest("li");
            //获得ul
            var parent = row.parent();
            if(row.parent().find("li").length<2){
                var ipts=row.find("input");
                ipts.each(function(i,v){
                    v.value="";
                })
            }else{
                row.remove();
                //处理索引
                var li_list = parent.find("li");
                li_list.each(function(i,v){
                	var input_arr = $(v).find("input");
                	$(input_arr[0]).attr("name","channel_urls["+i+"].channels_name");
                	$(input_arr[1]).attr("name","channel_urls["+i+"].channels_url");
                });
            }
        },
        addRow:function(ele){
            var self=$(ele);
            var row=self.closest("li");
            //获得ul
            var parent = row.parent();
            var li_length = parent.find("li").length;
            
            var vali=true;
            row.find("input").each(function(i,v){
                if(!$.trim(v.value)){
                	//如果input为空
                    v.focus();
                    vali=false;
                    return false;
                }
            });
            if(vali){
                var newRow=row.clone();
                newRow.find("input").each(function(i,v){
                    v.value="";
                });
                var input_arr = $(newRow).find("input");
            	$(input_arr[0]).attr("name","channel_urls["+li_length+"].channels_name");
            	$(input_arr[1]).attr("name","channel_urls["+li_length+"].channels_url");
                
                row.parent().append(newRow);
            }
        },
        openFileSelector:function(ele,num){
            var self=$(ele);
            var wrap=self.closest(".upload-wrap");
            var fileIpt=wrap.find(".fileHideIpt");
            fileIpt.attr("data-max",num)
            fileIpt.click();
        },
        userfileCatch:{},
        previewFile:function(evt,ele){
            // 如果浏览器不支持FileReader，则不处理
            if (!window.FileReader){
                alert("浏览器不支持本地预览图片");
                return false;
            }
        
        	var files = evt.target.files;
        
        
            var self=$(ele);
            var wrap=self.closest(".upload-wrap");
            var btnUpload=wrap.find(".btn-upload");
            var btnAdd=wrap.find(".btn-add");
            var fileType=wrap.attr("data-file-type");
            var usedFiles=ctrl.event.userfileCatch[wrap.attr("id")] ;
            if(!usedFiles){
                usedFiles=[];
                ctrl.event.userfileCatch[wrap.attr("id")]=usedFiles;
            }
            var maxLength=wrap.find(".upload-item").length+files.length-1;
            if(maxLength<=$(ele).attr("data-max")){
            $.each(files,function(i,f){
                console.dir(f);
                    var thumb=$($template($("#tUploaderThumb").html(),{}));
                    usedFiles.unshift({file:f,dom:thumb});
                    if (f.type.match('image.*')) {
                        var reader = new FileReader();
                        reader.onload = (function(theFile) {
                            return function(e) {
                                // img 元素
                                var img=new Image;
                                img.title="未上传："+ f.name;
                                thumb.insertBefore(btnAdd);

                                ctrl.event.operAddBtn(ele,btnAdd);

                                img.onload=function(){
                                    thumb.append(img);
                                };
                                img.src = e.target.result;
                            };
                        })(f);
                        reader.readAsDataURL(f);
                    }else{
                        var img=new Image();
                        img.title="未上传："+ f.name;
                        img.src="img/def_video.png";
                        thumb.append(img);
                        thumb.insertBefore(btnAdd);

                        ctrl.event.operAddBtn(ele,btnAdd);
                    }
               
            });
             }else{
                 alert("只能上传"+$(ele).attr("data-max")+"张图片！")
             }
          
            if(usedFiles.length>0){
                btnUpload.css({display:"inline-block"});
                btnUpload.prev().css({display:"none"});
            }else{
                btnUpload.hide();
            }
            
            self.val("");

        },
        delThumb:function(ele){
        	//debugger;
            var self=$(ele);
            var uploader = self.closest(".upload-wrap");
            var wrap=self.closest(".upload-item");
            var btnUpload = self.closest(".upload-wrap").find(".btn-upload");
            var filelist = wrap.closest(".upload-list");
//          if(confirm("是否继续删除")){
                wrap.addClass("deleted");
                wrap.remove();
//          }
            if(filelist.find("li").length == 0){
            	$(filelist[0]).html('<li style="  width: 130px;border: 1px solid #e5e5e5;padding: 5px 15px; text-align: center; cursor: pointer;" class="upload-item btn-add" onclick="ctrl.event.openFileSelector(this);" title="点击选择文件">点击选择文件</li>');
            }
            
            var thumbs=filelist.find(".btn-thumb");
            var hasUnloadedThumb=false;
            for(var i=0;i<thumbs.length;i++){
            	var t=thumbs.eq(i);
            	if(!t.hasClass("loaded")){
            		hasUnloadedThumb=true;break;
            	}
            }
            if(hasUnloadedThumb){
          	  btnUpload.css({display:"inline-block"});
	        }else{
              btnUpload.hide();
	        }
            
        },
        moveUpThumb:function(ele){
            var self=$(ele);
            var wrap=self.closest(".upload-item");
            wrap.insertBefore(wrap.prev());
        },
        moveDownThumb:function(ele){
            var self=$(ele);
            var wrap=self.closest(".upload-item");
            wrap.insertAfter(wrap.next());
        },
        startUpload:function(ele){
            var self=$(ele);
            var wrap=self.closest(".upload-wrap");
            var action=self.attr("data-action");
            var userFiles=ctrl.event.userfileCatch[wrap.attr("id")];
            ctrl.event.doUpload(userFiles,action,self);
        },
        doUpload:function(files,action,btnUpload){
            var f=files.pop();
            if(f){
                //上传对象
                console.dir(f);
                if(f.dom && !f.dom.hasClass("deleted")){
                    var dom= f.dom;
                    var processWrap=dom.find(".process-wrap");
                    var process=processWrap.find(".process");
                    var processInfo=processWrap.find(".process-info");
                    var uploader=new UtouuAjaxUploader({
                        url:action,
                        fileName:"file",
                        loadstart:function(){
                            processWrap.show();
                        },
                        load:function(rs){
                            processWrap.remove();
                            dom.addClass("loaded");
                            var name=dom.closest(".upload-wrap").attr("data-file-name");
                            var iptHide= $("<input type='hidden' name='"+name+"' value=''>").val(rs.data);//此处根据实际接口返回值进行调整
                            dom.find("img").attr("title","已上传："+rs.data);
                            dom.append(iptHide);    //上传完毕后讲所需参数值以隐藏input的形式加入表单
                        },
                        progress:function(percentComplete,total){
                            if(percentComplete>=100){
                                processInfo.text("完成");
                            }else{
                                processInfo.text(percentComplete+"%");
//                              process.css({top:percentComplete+"%"});
                            }
                        }
                    });
                    uploader.setFile(f.file);
                    uploader.send();
                }
            }
            if(files.length>0){
                ctrl.event.doUpload(files,action,btnUpload);
            }else{
                btnUpload.hide();
            }
        },
        operAddBtn:function(ele,btnAdd) {
        	//假设有multiple属性为可选择多个，如果没有该属性认为只可以上传一个文件 fangang
            var uploadflag = $(ele).attr("multiple");
            if(uploadflag == null || uploadflag == undefined){
            	//上传单张图片,删除添加按钮
            	
            	btnAdd.remove();
            }
        },
        uploadPropertyImage:function(evt,ele){
            var files = evt.target.files;
            var self=$(ele);
            var thumbWrap=self.closest(".goods-property-item").find(".thumb");
            if(files.length>0){
                var f=files[0];
                var uploader=new UtouuAjaxUploader({
                    url:ctrl.url.imageUpload,
                    fileName:"file",
                    load:function(rs){
                        if(rs.success){
                            var name="goodsImageUrl"   ;//根据业务添加 hidden 的name
                            var iptHide= $("<input type='hidden' name='"+name+"' value=''>");
                            dom.append(iptHide);
                        }

                    },
                    progress:function(percentComplete,total){
                        if(percentComplete>=100){
                            processInfo.text("完成");
                        }else{
                            processInfo.text(percentComplete+"%");
//                          process.css({top:percentComplete+"%"});
                        }
                    }
                });
                uploader.setFile(f.file);
                uploader.send();
            }
        }
    }

};
